<?php

declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: yangfan
 * Date: 2019/10/31
 * Time: 4:25 PM
 */

namespace App\Services;

use App\BO\Product\ProductBO;
use App\Entity\ProductEntity;
use App\Entity\ProductSkuEntity;
use App\Inc\OrderInc;
use App\Models\ProductSku;
use App\Services\api\IProductSkuService;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class ProductSkuService implements IProductSkuService
{
    /**
     * @return ProductSkuEntity/null
     */
    public function getProductSkuListFirst(int $productId)
    {
        $model = ProductSku::where('product_id', '=', $productId)->first();
        if ($model === null) {
            return null;
        } else {
            return new ProductSkuEntity($model);
        }
    }

    /**
     * @return ProductSkuEntity/null
     */
    public function findOne(int $productSkuId)
    {
        return ProductSkuEntity::find($productSkuId);
    }

    /**
     * @deprecated
     * {@inheritdoc}
     */
    public function getProductSkus(ProductEntity $productEntity)
    {
        $skus = productSku::with(['productsUnit'])
            ->where('product_id', $productEntity->getId())
            ->where('city_id', $productEntity->getProductCity())

            ->where('purchase_product_id', 0)  // 不能为加购 sku

            ->where(function ($query) {
                $query->where('begin_sale', '<=', Carbon::now())
                    ->orWhereNull('begin_sale');
            })

            ->where(function ($query) {
                $query->where('stop_sale', '>=', Carbon::now())
                    ->orWhereNull('stop_sale');
            })

            ->where('sku_show_type', $productEntity->getProductShowType())
            ->where('on_sale', OrderInc::PRODUCT_SKU_ON_SALE_开启)
            ->orderBy('order_by', 'asc')
            ->get();

        if ($skus->isEmpty()) {
            Log::info("当前产品无sku  产品id: {$productEntity->getId()}, 城市id: {$productEntity->getProductCity()}, 显示类型: {$productEntity->getProductShowType()}, 是否在售:[在售]");
        }

        return $skus;
    }

    /**
     * {@inheritdoc}
     */
    public function getProductSkusByProductBO(ProductBO $productBO)
    {
        return productSku::with(['productsUnit'])
            ->where('product_id', $productBO->getId())
            ->where('city_id', $productBO->getCityProductInfo()->getProductCity())

            ->where('purchase_product_id', 0)  // 不能为加购 sku

            ->where(function ($query) {
                $query->where('begin_sale', '<=', Carbon::now())
                    ->orWhereNull('begin_sale');
            })

            ->where(function ($query) {
                $query->where('stop_sale', '>=', Carbon::now())
                    ->orWhereNull('stop_sale');
            })

            ->where('sku_show_type', $productBO->getProductShowType())
            ->where('on_sale', OrderInc::PRODUCT_SKU_ON_SALE_开启)
            ->orderBy('order_by', 'asc')
            ->get();
    }
}
